package com.example.fragment;

import android.os.Bundle;
import android.util.SparseArray;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements ExerciseFragment.DataCallback {
    private SparseArray<Fragment> fragments;
    private TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvTitle = findViewById(R.id.tv_title);

        // 初始化 fragment列表
        initFragments();

        // 加载 fragment
        replaceFragment(fragments.get(R.id.btn_execise));

        // 按钮事件切换fragment
        RadioGroup btnGroup = findViewById(R.id.btn_group);
        btnGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                replaceFragment(fragments.get(checkedId));
            }
        });
    }

    private void initFragments() {
        fragments = new SparseArray<>();
        fragments.put(R.id.btn_course, CourseFragment.newInstance(1));
        fragments.put(R.id.btn_execise, ExerciseFragment.newInstance("exercise"));
        fragments.put(R.id.btn_message, new MessageFragment());
        fragments.put(R.id.btn_my, new SettingsFragment());
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.layout_content, fragment);
        transaction.commit();
    }

    // 更新标题
    @Override
    public void putTitle(String title) {
        tvTitle.setText(title);
    }
}